<template>
  <div class="user-info-head" @click="editCropper()">
    <img :src="userStore.avatar" title="点击上传头像" class="img-circle img-lg" />
    <a-modal
      v-model:open="open"
      :title="title"
      :width="800"
      @ok="uploadImg"
      @cancel="closeDialog"
      cancelText="取消"
      okText="提交"
    >
      <a-row>
        <a-col :xs="24" :md="12" :style="{ height: '350px' }">
          <vue-cropper
            v-if="visible"
            ref="cropper"
            :img="options.img"
            :info="true"
            :auto-crop="options.autoCrop"
            :auto-crop-width="options.autoCropWidth"
            :auto-crop-height="options.autoCropHeight"
            :fixed-box="options.fixedBox"
            :output-type="options.outputType"
            @real-time="realTime"
          />
        </a-col>
        <a-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div class="avatar-upload-preview">
            <img :src="options.previews.url" :style="options.previews.img" />
          </div>
        </a-col>
      </a-row>
      <br />
      <a-row>
        <a-col :span="2">
          <a-upload
            ref="uploadRef"
            accept="image/*"
            :show-upload-list="false"
            :before-upload="beforeUpload"
          >
            <a-button>
              选择
              <template #icon><upload-outlined /></template>
            </a-button>
          </a-upload>
        </a-col>
        <a-col :span="2" :offset="2">
          <a-button @click="changeScale(1)">
            <template #icon><plus-outlined /></template>
          </a-button>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button @click="changeScale(-1)">
            <template #icon><minus-outlined /></template>
          </a-button>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button @click="rotateLeft()">
            <template #icon><undo-outlined /></template>
          </a-button>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button @click="rotateRight()">
            <template #icon><redo-outlined /></template>
          </a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script setup lang="ts" name="UserAvatar">
import { ref, reactive, watch } from 'vue';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { uploadAvatar } from '@/api/front/user';
import useUserStore from '@/store/modules/user';
import { message } from 'ant-design-vue';
import { 
  UploadOutlined,
  PlusOutlined,
  MinusOutlined,
  UndoOutlined,
  RedoOutlined
} from '@ant-design/icons-vue';

interface Options {
  img: string | any; // 裁剪图片的地址
  autoCrop: boolean; // 是否默认生成截图框
  autoCropWidth: number; // 默认生成截图框宽度
  autoCropHeight: number; // 默认生成截图框高度
  fixedBox: boolean; // 固定截图框大小 不允许改变
  fileName: string;
  previews: any; // 预览数据
  outputType: string;
  visible: boolean;
}

const userStore = useUserStore();

const open = ref(false);
const visible = ref(false);
const title = ref('修改头像');

// 监听open值的变化
watch(open, (newValue) => {
  visible.value = newValue;
});

const cropper = ref<any>({});
//图片裁剪数据
const options = reactive<Options>({
  img: "",
  autoCrop: true,
  autoCropWidth: 200,
  autoCropHeight: 200,
  fixedBox: true,
  outputType: 'png',
  fileName: '',
  previews: {},
  visible: false
});

/** 编辑头像 */
const editCropper = () => {
  open.value = true;
  message.info('请先选择图片');
};


/** 向左旋转 */
const rotateLeft = () => {
  cropper.value.rotateLeft();
};

/** 向右旋转 */
const rotateRight = () => {
  cropper.value.rotateRight();
};

/** 图片缩放 */
const changeScale = (num: number) => {
  num = num || 1;
  cropper.value.changeScale(num);
};

/** 上传预处理 */
const beforeUpload = (file: File): boolean => {
  if (file.type.indexOf('image/') == -1) {
    message.error('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。');
    return false;
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      options.img = reader.result;
      options.fileName = file.name;
    };
    return false;
  }
};

/** 上传图片 */
const uploadImg = async () => {
  if (!options.fileName) {
    message.error('请先选择图片');
    return;
  }
  
  try {
    cropper.value.getCropBlob(async (data: any) => {
      if (!data) {
        message.error('获取裁剪数据失败');
        return;
      }
      let formData = new FormData();
      formData.append('avatarfile', data, options.fileName);
      
      const res = await uploadAvatar(formData);
      open.value = false;
      options.img = res.data.imgUrl;
      userStore.setAvatar(res.data.imgUrl);
      message.success('修改成功');
      visible.value = false;
    });
  } catch (error) {
    console.error('裁剪失败:', error);
    message.error('图片处理失败，请重试');
  }
};

/** 实时预览 */
const realTime = (data: any) => {
  options.previews = data;
};

/** 关闭窗口 */
const closeDialog = () => {
  options.img = '';
  options.visible = false;
};
</script>

<style lang="scss" scoped>
.user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
  text-align: center;
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 110px;
  border-radius: 50%;
}

.img-circle {
  border-radius: 50%;
}

.img-lg {
  width: 120px;
  height: 120px;
}

.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>
